#include "init.h"

#include "type.h"

void sdram_init(void) {
    BWSCON = 0x22000000;
    BANKCON6 = 0x18001;
    BANKCON7 = 0x18001;
    REFRESH = 0x8404F5;
    BANKSIZE = 0xB1;
    MRSRB6 = 0x20;
}

int sdram_test(void) {
    vu8 *p = (vu8 *)0x30000000;
    int i;

    for (i = 0; i < 1000; i++) {
        p[i] = 0xAA;
    }

    for (i = 0; i < 1000; i++) {
        if (p[i] != 0xAA) {
            return -1;
        }
    }
    return 0;
}

int isBootFromNorFlash(void) {
    volatile uint32 *p = (volatile uint32 *)0;
    uint32 val = *p;

    *p = 0x12345678;
    if (*p == 0x12345678) {
        *p = val;
        return 0;
    }
    return 1;
}

void nand_init(void);
void nand_read(unsigned int addr, unsigned char *buf, unsigned int len);

void copy2sdram(void) {
    /* 要从lds文件中获得 __code_start, __bss_start
     * 然后从0地址把数据复制到__code_start
     */

    extern int __code_start, __bss_start;

    volatile uint32 *dest = (volatile uint32 *)&__code_start;
    volatile uint32 *end = (volatile uint32 *)&__bss_start;
    volatile uint32 *src = (volatile uint32 *)0;
    int len;

    len = ((int)&__bss_start) - ((int)&__code_start);

    if (isBootFromNorFlash()) {
        while (dest < end) {
            *dest++ = *src++;
        }
    } else {
        nand_init();
        nand_read(*src, dest, len);
    }
}

void clean_bss(void) {
    /* 要从lds文件中获得 __bss_start, _end
     */
    extern int __end, __bss_start;

    volatile uint32 *start = (volatile uint32 *)&__bss_start;
    volatile uint32 *end = (volatile uint32 *)&__end;

    while (start <= end) {
        *start++ = 0;
    }
}
